//
//  HOTakePhotoMgr.m
//  微度报修
//
//  Created by foguo-mac-1 on 6/9/16.
//  Copyright © 2016 WeiDu. All rights reserved.
//

#import "HOTakePhotoMgr.h"
#import "ELCImagePickerController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "HOUtils.h"

@interface HOTakePhotoMgr()<UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, ELCImagePickerControllerDelegate, UIGestureRecognizerDelegate>
{
	
}
@property(nonatomic ,retain)UIActionSheet *actionSheetImpl;
@property(nonatomic, retain)UITapGestureRecognizer *tapForSheet;
@property(nonatomic, retain)UIImagePickerController * picker;
@end
@implementation HOTakePhotoMgr
@synthesize delegate;
#pragma mark

- (void)takePhoto:(id)sender
{
	if(self.onlyCanTakePhoto)
	{
		UIImagePickerControllerSourceType sourceType=UIImagePickerControllerSourceTypeCamera;
		
		if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
			sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
		}
		self.picker = [[[UIImagePickerController alloc]init] autorelease];
		self.picker.delegate = self;
		self.picker.allowsEditing = YES;
		self.picker.sourceType = sourceType;
		[self.viewController presentViewController:self.picker animated:YES completion:nil];
	}
	else
	{
		[self.delegate hideKeyboard];
		if(self.actionSheetImpl == nil)
		{
			self.actionSheetImpl = [[[UIActionSheet alloc]
									initWithTitle:nil
									delegate:self
									cancelButtonTitle:@"取消"
									destructiveButtonTitle:@"拍照"
									otherButtonTitles:@"从相册选择",nil] autorelease];
		}
		
		self.tapForSheet = [[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTapFrom:)] autorelease];
		self.tapForSheet.cancelsTouchesInView = NO;
		self.tapForSheet.delegate = self;
		[self.actionSheetImpl.window addGestureRecognizer:self.tapForSheet];
		[self.actionSheetImpl showInView:self.viewController.view];
	}
}

- (void)handleTapFrom:(UITapGestureRecognizer *)gesture
{
	if(self.actionSheetImpl != nil)
	{
		[self.actionSheetImpl dismissWithClickedButtonIndex:3 animated:YES];
		self.actionSheetImpl = nil;
		
	}
}
#pragma mark -- UIActionSheetDelegate implement methods
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if(buttonIndex  == 0)
	{
		UIImagePickerControllerSourceType sourceType=UIImagePickerControllerSourceTypeCamera;
		
		if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
			sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
		}
		UIImagePickerController * picker = [[UIImagePickerController alloc]init];
		picker.delegate = self;
		picker.allowsEditing = YES;
		picker.sourceType = sourceType;
		[self.viewController presentViewController:picker animated:YES completion:nil];
		[picker release];
	}
	else if(buttonIndex == 1)
	{
		
		ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initImagePicker];
		
		elcPicker.maximumImagesCount = [self.delegate getRemainPhotoCount];
		elcPicker.returnsOriginalImage = YES; //Only return the fullScreenImage, not the fullResolutionImage
		elcPicker.returnsImage = YES; //Return UIimage if YES. If NO, only return asset location information
		elcPicker.onOrder = YES; //For multiple image selection, display and return selected order of images
		elcPicker.imagePickerDelegate = self;
		
		//Present modally
		[self.viewController presentViewController:elcPicker animated:YES completion:nil];
		
		// Release if not using ARC
		[elcPicker release];
	}
	[self.actionSheetImpl.window removeGestureRecognizer:self.tapForSheet];
	self.actionSheetImpl = nil;
	
}
#pragma nark -

- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info;
{
	[picker dismissViewControllerAnimated:YES completion:NULL];
	NSMutableArray *images = [NSMutableArray arrayWithCapacity:[info count]];
	for (NSDictionary *dict in info) {
		if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypePhoto)
		{
			if ([dict objectForKey:UIImagePickerControllerOriginalImage])
			{
				UIImage* image = [dict objectForKey:UIImagePickerControllerOriginalImage];
				CGSize newSize = CGSizeZero;
				if (IS_IPHONE_5_SCREEN)
				{
					newSize = CGSizeMake(640, 568*2);
				}else
				{
					newSize = CGSizeMake(640, 960);
				}
				CGFloat originalRatio = image.size.width / image.size.height;
				CGFloat wantedRatio = newSize.width / newSize.height;
				CGFloat scale = 1;
				
				if (originalRatio < wantedRatio)
				{
					scale = newSize.height / image.size.height;
				}
				else
				{
					scale = newSize.width / image.size.width;
				}
				
				//			UIImage *originImage = [UIImage imageWithCGImage:imgRef scale:scale orientation:(UIImageOrientation)assetRep.orientation];
				NSData *data = UIImageJPEGRepresentation(image, 0.1);
				UIImage *scaleImage = [UIImage imageWithData:data];
				[images addObject:scaleImage];
			} else
			{
//				LogNor(@"UIImagePickerControllerReferenceURL = %@", dict);
			}
		}
		else
		{
//			LogNor(@"Uknown asset type");
		}
	}
	if([self.delegate respondsToSelector:@selector(didPickImages:)])
	{
		[self.delegate didPickImages:images];
	}
	
}

-(UIView *)findView:(UIView *)aView withName:(NSString *)name{
	Class cl = [aView class];
	NSString *desc = [cl description];
	
	if ([name isEqualToString:desc])
		return aView;
	
	for (NSUInteger i = 0; i < [aView.subviews count]; i++)
	{
		UIView *subView = [aView.subviews objectAtIndex:i];
		subView = [self findView:subView withName:name];
		if (subView)
			return subView;
	}
	return nil;
}
-(void)addSomeElements:(UIViewController *)viewController{
	
	
	UIView *PLCameraView=[self findView:self.picker.view withName:@"PLCameraView"];
	UIView *bottomBar=[self findView:PLCameraView withName:@"PLCropOverlayBottomBar"];
	UIImageView *bottomBarImageForSave = [bottomBar.subviews objectAtIndex:0];
	UIButton *retakeButton=[bottomBarImageForSave.subviews objectAtIndex:0];
	[retakeButton setTitle:@"重拍" forState:UIControlStateNormal];  //左下角按钮
	UIButton *useButton=[bottomBarImageForSave.subviews objectAtIndex:1];
	[useButton setTitle:@"上传" forState:UIControlStateNormal];  //右下角按钮
}
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
 
	[self addSomeElements:viewController];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
	UIImage * originalImage =[info objectForKey:UIImagePickerControllerOriginalImage];
	NSData *data = UIImageJPEGRepresentation(originalImage, 0.1);
	UIImage *scaleImage = [UIImage imageWithData:data];
	if([self.delegate respondsToSelector:@selector(didPickImages:)])
	{
		[self.delegate didPickImages:@[scaleImage]];
	}
	[picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker
{
	[picker dismissViewControllerAnimated:YES completion:NULL];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
	//    LogNor(@"取消选择");
	[picker dismissViewControllerAnimated:YES completion:NULL];
}

- (void)dealloc
{
	self.viewController = nil;
	
	self.actionSheetImpl = nil;
	self.tapForSheet = nil;
	self.picker = nil;
	[super dealloc];
}
@end
